23. Exercise: Adding Sharing with an Intent

7 Exercise- Adding Sharing With An Intent- 2020

Update Note

In the video above, the following individual lines of code in GameWonFragment.kt file have been updated:

  1. val args = GameWonFragmentArgs.fromBundle(arguments) - The argument passed to fromBundle() method has changed.

  2. override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?)

  3. inflater?.inflate(R.menu.winner_menu, menu)

  4. if (null == getShareIntent().resolveActivity(activity!!.packageManager)) {

  5. menu?.findItem(R.id.share)?.setVisible(false)

  6. override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) {

The updated code is shown in the instructions below. Alternatively, you can refer to the updated GameWonFragment.kt file in the relevant branch of the andfun-kotlin-android-trivia repo.

1. Add setHasOptionsMenu(true) to onCreateView() in our GameWonFragment

We’ll start by adding setHasOptionsMenu(true) to onCreateView() in our GameWonFragment.

// Declaring that our Fragment has a Menu
binding.nextMatchButton.setOnClickListener { view: View ->
 view.findNavController().navigate(GameWonFragmentDirections.actionGameWonFragmentToGameFragment())
}
setHasOptionsMenu(true)

2. Create a getShareIntent method. Get the args and build the shareIntent inside.

We’ll create a getShareIntent method and move our GameWonFragmentArgs.fromBundle there. We’ll use shareCompat to create our share Implicit intent. We can call ShareCompat.IntentBuilder.from(activity), set our text, and then set the MIME type, finishing off by building our intent.

// Creating our Share Intent
private fun getShareIntent() : Intent {
   val args = GameWonFragmentArgs.fromBundle(requireArguments())
   val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.setType("text/plain")
            .putExtra(Intent.EXTRA_TEXT, getString(R.string.share_success_text, args.numCorrect, args.numQuestions))
   return shareIntent
}

3. Create a shareSuccess method that starts the activity from the share Intent

Next, we’ll create our shareSuccess method, which gets the Intent from getShareIntent and calls startActivity to begin sharing.

// Starting an Activity with our new Intent
private fun shareSuccess() {
   startActivity(getShareIntent())
}

4. Override onCreateOptionsMenu and inflate our winner_menu.

Override onCreateOptionsMenu and begin by inflating the winner_menu. Then we’ll get the shareIntent using getShareIntent() and call resolveActivity using the packageManger to make sure our shareIntent resolves to an activity.

5. Hide the sharing menu item if the sharing intent doesn’t resolve to an Activity

If the result equals null, which means that it doesn’t resolve, we find our sharing menu item from the inflated menu and set its visibility to false.

// Showing the Share Menu Item Dynamically
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
   super.onCreateOptionsMenu(menu, inflater)
   inflater.inflate(R.menu.winner_menu, menu)
   // check if the activity resolves
   if (null == getShareIntent().resolveActivity(requireActivity().packageManager)) {
       // hide the menu item if it doesn't resolve
       menu.findItem(R.id.share)?.isVisible = false
   }
}

6. Override onOptionsIemSelected to link the menu to the shareSuccess action

Override onOptionsItemSelected. When the menuitem id matches R.id.share, call the shareSuccess method.

// Sharing from the Menu
override fun onOptionsItemSelected(item: MenuItem): Boolean {        
   when (item.itemId) {
       R.id.share -> shareSuccess()
   }
   return super.onOptionsItemSelected(item)
}

And we’re done! If there is an available destination for our shareIntent, the icon will appear and we can share. Otherwise, it will not be available.

If you want to start at this step, you can download this exercise code from: Step.08-Exercise-Sharing-Success.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.08-Solution-Sharing-Success or diff.

Task Description:

Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

And now we really sharing --- with Intent.

Solution: Step.08-Solution-Sharing-Success or git diff